package scatter.role.rest.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import scatter.common.rest.service.IBaseAddUpdateQueryFormServiceImpl;
import scatter.role.pojo.form.RoleAddForm;
import scatter.role.pojo.form.RolePageQueryForm;
import scatter.role.pojo.form.RoleUpdateForm;
import scatter.role.pojo.po.Role;
import scatter.role.pojo.po.RoleFuncRel;
import scatter.role.pojo.po.RoleUserRel;
import scatter.role.rest.mapper.RoleMapper;
import scatter.role.rest.service.IRoleFuncRelService;
import scatter.role.rest.service.IRoleService;
import scatter.role.rest.service.IRoleUserRelService;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author yw
 * @since 2020-12-15
 */
@Service
@Transactional
public class RoleServiceImpl extends IBaseAddUpdateQueryFormServiceImpl<RoleMapper, Role, RoleAddForm, RoleUpdateForm, RolePageQueryForm> implements IRoleService {

    @Autowired
    private IRoleUserRelService iRoleUserRelService;

    @Autowired
    private IRoleFuncRelService iRoleFuncRelService;
    @Override
    public void preAdd(RoleAddForm addForm,Role po) {
        super.preAdd(addForm,po);
        po.setIsDisabled(false);
        if (!isStrEmpty(addForm.getCode())) {
            // 角色编码已存在不能添加
            assertByColumn(addForm.getCode(),Role::getCode,false);
        }

    }

    @Override
    public void preUpdate(RoleUpdateForm updateForm,Role po) {
        super.preUpdate(updateForm,po);
        if (!isStrEmpty(updateForm.getCode())) {
            Role byId = getById(updateForm.getId());
            // 如果角色编码有改动
            if (!isEqual(updateForm.getCode(), byId.getCode())) {
                // 角色编码已存在不能修改
                assertByColumn(updateForm.getCode(),Role::getCode,false);
            }
        }

    }

    @Override
    public List<Role> getByUserId(String userId,Boolean isDisabled) {
        List<RoleUserRel> byUserId = iRoleUserRelService.getByUserId(userId);
        if (isEmpty(byUserId)) {
            return new ArrayList<>();
        }
       return list(Wrappers.<Role>lambdaQuery().in(Role::getId,byUserId.stream().map(RoleUserRel::getRoleId).collect(Collectors.toList()))
        .eq(isDisabled != null,Role::getIsDisabled,isDisabled));

    }

    @Override
    public List<Role> getByFuncId(String funcId,Boolean isDisabled) {
        List<RoleFuncRel> byFuncId = iRoleFuncRelService.getByFuncId(funcId);
        if (isEmpty(byFuncId)) {
            return new ArrayList<>();
        }
        return list(Wrappers.<Role>lambdaQuery().in(Role::getId,byFuncId.stream().map(RoleFuncRel::getRoleId).collect(Collectors.toList()))
                .eq(isDisabled != null,Role::getIsDisabled,isDisabled));
    }
}
